#!/usr/bin/env python3
"""
MySQL5 MCP Server

面向 MySQL5 数据库软件的 MCP Server，提供 MySQL 服务管理相关的命令行操作。

MCP tools 列表：
- mysql_service_start: 启动 MySQL 服务
- mysql_service_stop: 停止 MySQL 服务
- mysql_service_restart: 重启 MySQL 服务  
- mysql_service_reload: 重载 MySQL 服务
- mysql_service_status: 检查 MySQL 服务状态
"""

import subprocess
import shlex
from typing import Dict, Any
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("MySQL5 MCP Server")


@mcp.tool()
def mysql_service_start() -> Dict[str, Any]:
    """
    启动 MySQL 服务
    
    返回:
        Dict: 包含执行结果的 JSON 结构
        {
            "success": bool,      # 是否执行成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    cmd = "systemctl start mysqld.service"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }


@mcp.tool()
def mysql_service_stop() -> Dict[str, Any]:
    """
    停止 MySQL 服务
    
    返回:
        Dict: 包含执行结果的 JSON 结构
        {
            "success": bool,      # 是否执行成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    cmd = "systemctl stop mysqld.service"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }


@mcp.tool()
def mysql_service_restart() -> Dict[str, Any]:
    """
    重启 MySQL 服务
    
    返回:
        Dict: 包含执行结果的 JSON 结构
        {
            "success": bool,      # 是否执行成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    cmd = "systemctl restart mysqld.service"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }


@mcp.tool()
def mysql_service_reload() -> Dict[str, Any]:
    """
    重载 MySQL 服务
    
    返回:
        Dict: 包含执行结果的 JSON 结构
        {
            "success": bool,      # 是否执行成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    cmd = "systemctl reload mysqld.service"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }


@mcp.tool()
def mysql_service_status() -> Dict[str, Any]:
    """
    检查 MySQL 服务状态
    
    返回:
        Dict: 包含执行结果的 JSON 结构
        {
            "success": bool,      # 是否执行成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    cmd = "systemctl status mysqld.service"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }


if __name__ == "__main__":
    mcp.run()